import React, { Component } from 'react';
import { Col, Modal, Row, Select, Form, message } from 'antd';
import { MinusCircleOutlined, } from '@ant-design/icons';
// import { LeftAssociationIcon } from './SvgComponent';
import { FormInstance } from 'antd/lib/form';
import { nodeJoin, componentJoin, resetNodeJoin } from 'src/services/DataManage';

interface Iprops {
	modalVisibleValue:boolean
	modalVisible:any
	relationData:any
	addNodeFunc:any
	addRelation:any
	moId:any
	currentData:any
	targetFieldTableName?:any
	sourceFieldTableName?:any
	form?:any
	edit?:any
	fieldOrder?:any
	addDataFunc?:any
	setOutDataFunc:any
}

class AssociationModal extends Component<Iprops,any> {

	state = {
		fieldList: [],
		sourceField: [],
		targetField: [],
		sourceCurrentSelected: '',
		targetCurrentSelected: '',
		sourceFieldTableName: '',
		targetFieldTableName: '',
		formSelectItem: [ 0 ],
		show: this.props.modalVisibleValue
	}

	formRef = React.createRef<FormInstance>()
	
	handleTable = ( value,field ) => {
		let d = {};
		d[`${field}TableName`] = value;
		this.setState( d );
		let data = this.props.relationData.filter( item => item.data.code === value );
		let tmp = {};
		tmp[field] = data[0].data.model.fieldMappings;
		this.setState( tmp );
	}

	
	handlFieldList = ( item ) => {
		
		// const { sourceCurrentSelected,targetCurrentSelected } = this.state;
		// // //当两个选项值不为空时
		// if ( sourceCurrentSelected && targetCurrentSelected ) {
		// 	//如果选项存在即返回false删除
		// 	let flist = this.state.fieldList.filter( item => !( item.leftField === sourceCurrentSelected&& item.rightField === targetCurrentSelected ) );
		// 	if( flist.length === this.state.fieldList.length ) {
		// 		flist.push( { leftField: sourceCurrentSelected,rightField: targetCurrentSelected } );
		// 		this.setState(
		// 			{ fieldList: flist, },() => {  }
		// 		);
		// 	}
		// }
		this.formRef.current.resetFields( [ `${item}-left`,`${item}-right` ] );
		this.setState( { formSelectItem: this.state.formSelectItem.filter( it => it !== item ) } );

	}
	
	handleSelectChange = ( value,field,flag ) => {
		const { formSelectItem } = this.state;
		let last = formSelectItem[formSelectItem.length - 1];
		let tmp = {};
		tmp[field] = value;
		this.setState(  tmp,() => {
			//当左右两边都选择了添加新项并且flag在
			if( this.state.sourceCurrentSelected&&this.state.targetCurrentSelected ) {
				//最后一个就添加新的选项
				if( flag === last ) {
					formSelectItem.push( last + 1 );
					this.setState( {
						'formSelectItem': formSelectItem ,
						sourceCurrentSelected: '',
						targetCurrentSelected: ''
					} );
				}
			}
		}
		);
	}
	
	delField = index => {
		let flist = JSON.parse( JSON.stringify( this.state.fieldList ) );
		flist.splice( index,1 );
		this.setState(
			{ fieldList: flist }
		);
	}

	handeleSelectValue = values => {
		return Object.keys( values ).filter( item => item.indexOf( '-' ) !== -1&&values[item] )
			.filter( item => item.indexOf( 'left' )!==-1 )
			.map( item => {
				let right = item.replace( 'left','' ) ;
				return { leftField: values[item],
					rightField: values[`${right  }right`] };
			}
			).map( item => {return { leftField: JSON.parse( item.leftField ).temp,rightField: JSON.parse( item.rightField ).temp };} );
	}
	
	
	
	handleSubmit = () => {
		this.formRef.current.validateFields().then(  async values => {
			let joinFields =  this.handeleSelectValue( values );
			let ldata= this.props.relationData.filter( item => item.data.code === values.leftTableName )[0];
			let rdata = this.props.relationData.filter( item => item.data.code === values.rightTableName )[0];
			let data = {
				'fields': [],
				'position': 1,
				'tables': [
					{
						'joinFields': [],
						'joinType': '',
						'leftTableName': '',
						'tableName': values.leftTableName
					},
					{
						'joinFields': joinFields,
						'joinType': 'left',
						'leftTableName': values.leftTableName,
						'tableName': values.rightTableName,
					},
				]
			};
			
			let info = null;
			if( this.props.currentData.edit ) {
				const { code,name } = this.props.currentData;
				info = await resetNodeJoin( { data: { ...data,componentCode: code,componentName: name  } } );
			}else {
				//引入关联组件
				info = await nodeJoin( { data: { ...data,'modelId': this.props.moId } } );
			}
			if ( info.data.success ) {
				let left = { data: {
					success: false
				} };
				let right = { data: {
					success: false
				} };
				if( !this.props.currentData.edit ) {
					let mData = { 'fromComponentCode': ldata.data.code, 'modelId': this.props.moId, 'position': 1, 'toComponentCode': info.data.data.code };
					let nData = { 'fromComponentCode': rdata.data.code, 'modelId': this.props.moId, 'position': 1, 'toComponentCode': info.data.data.code };
					//左边节点和关联后的节点连接
					left = await componentJoin( { data: mData } );
					//右边节点和关联后的节点连接
					right = await componentJoin( { data: nData } );
				}else {
					const data = info.data.data;
					data['edit'] = true;
					const t = await this.props.addNodeFunc( { ...data,
						form: values,
						fieldOrder: this.state.formSelectItem,
						currentData: this.props.currentData.currentData,
						targetFieldTableName: this.state.targetFieldTableName,
						sourceFieldTableName: this.state.sourceFieldTableName,
						sourceField: this.state.sourceField,
						targetField: this.state.targetField,
						x: this.props.currentData.x,
						y: this.props.currentData.y,
						modelId: this.props.moId,
						nodeType: 'relate',
						nodeShapeTpye: 'apartment',
						style: { 'primaryColor': '#0066FF' },
						shape: 'SimplicityNode' },true );
					if( t ) {
						this.handleClose();
					}
					//更新结束
					return ;
				}
				if ( left.data.success && right.data.success ) {
					// //添加node节点
					const t = await this.props.addNodeFunc( { ...info.data.data,
						form: values,
						fieldOrder: this.state.formSelectItem,
						currentData: this.props.currentData,
						targetFieldTableName: this.state.targetFieldTableName,
						sourceFieldTableName: this.state.sourceFieldTableName,
						sourceField: this.state.sourceField,
						targetField: this.state.targetField,
						x: ( ldata.x + rdata.x )/2,
						y: ( ldata.y + rdata.y )/2,
						modelId: this.props.moId,
						nodeType: 'relate',
						nodeShapeTpye: 'apartment',
						style: { 'primaryColor': '#0066FF' },
						shape: 'SimplicityNode' } );
					if( t ) {
						//左节点与关联node连线
						this.props.addRelation( { source: ldata.id ,result: info.data.data.id } );
						this.props.addRelation( { source: rdata.id ,result: info.data.data.id } );
						this.handleClose();
					}
				}else {
					if( !this.props.currentData.edit ) {
						message.error( '关联失败请重试' );
					}
				}
			}
		} );
	}
	
	//重置数据
	handleClose = () => {
		let data = this.props.currentData;
		delete data.edit;
		this.props.setOutDataFunc( data );
		this.formRef.current.resetFields();
		this.setState( {
			fieldList: [],
			sourceField: [],
			targetField: [],
			sourceCurrentSelected: '',
			targetCurrentSelected: '',
			sourceFieldTableName: '',
			targetFieldTableName: '',
			formSelectItem: [ 0 ],
		} ,() => this.props.modalVisible( 'relationVisible',false ) );
	}

	componentDidMount(): void {
		this.setState( { show: this.props.modalVisibleValue } );
		if( this.state.show&&this.props.currentData.edit ) {
			const { fieldOrder,sourceFieldTableName,targetFieldTableName,form } = this.props.currentData;
			this.handleTable( targetFieldTableName,'targetField' );
			this.handleTable( sourceFieldTableName,'sourceField' );
			this.setState( { formSelectItem: fieldOrder },() => {
				this.formRef.current.setFieldsValue( form );
			} );
		}
	}

	componentDidUpdate( prevProps: Readonly<Iprops>, prevState: Readonly<any>, snapshot?: any ): void {
		if( ( this.props.modalVisibleValue !== prevProps.modalVisibleValue ) && ( !this.props.currentData.edit ) ) {
			const { code,model } = this.props.currentData;
			// this.handleTable( targetFieldTableName,'targetField' );
			this.setState( { sourceFieldTableName: code,sourceField: model.fieldMappings } );
		}
		if( ( this.props.modalVisibleValue !== prevProps.modalVisibleValue )&&this.props.currentData.edit ) {
			const { fieldOrder,sourceFieldTableName,targetFieldTableName,form } = this.props.currentData;
			this.handleTable( targetFieldTableName,'targetField' );
			this.handleTable( sourceFieldTableName,'sourceField' );
			this.setState( { formSelectItem: fieldOrder },() => {
				this.formRef.current.setFieldsValue( form );
			} );
		}
	}


	render() {
		let title = '关联数据';
		if( this.props.currentData.edit ) {
			title += ' (编辑)';
		}
		let currentData = this.props.currentData;
		return (
			<Modal
				visible={this.props.modalVisibleValue}
				onOk={this.handleSubmit}
				onCancel={this.handleClose}
				mask={false} maskClosable={false}
				cancelText={'取消'}
				okText={'确定'}
				title={title}
			>
				<Form ref={this.formRef} initialValues={{
					leftTableName: currentData.code,
					// rightTableName: this.props.currentData.selcetTableName

				}}>
					<Row gutter={[ 16,0 ]} style={{ marginBottom: '8px' }}>
						<Col span={11}>表</Col>
						<Col span={1}/>
						<Col span={11}>选择关联表</Col>
					</Row>
					<Row gutter={[ 16,16 ]}>
						<Col span={10}>
							<Form.Item name="leftTableName" noStyle={true}>
								<Select key="targetField" style={{ width: 180 }} disabled={currentData.edit} onChange={ value => {this.handleTable( value,'sourceField' );} }>
									{
										this.props.relationData.filter( item => item.data.tableName ).map( item => {
											return (
												<Select.Option key={`${item.data.id}t`} value={item.data.code} >
													{item.label}
												</Select.Option>
											);
										} )
									}
								</Select>
							</Form.Item>
						</Col>
						<Col span={2}><span className="iconfont" style={{ fontSize: '16px' }}>&#xe732;</span></Col>
						<Col span={10}>
							<Form.Item name="rightTableName" noStyle={true}>
								<Select key="targetField" style={{ width: 180 }} disabled={currentData.edit} onChange={ value => {this.handleTable( value,'targetField' );} }>
									{
										this.props.relationData.filter( item => item.data.tableName ).map( item => {
											return (
												<Select.Option key={`${item.data.id}t`} value={item.data.code} >
													{item.label}
												</Select.Option>
											);
										} )
									}
								</Select>
							</Form.Item>
						</Col>
					</Row>
					<Row gutter={[ 16,0 ]} style={{ marginBottom: '8px' }}>
					  <Col>关联字段选择</Col>
					</Row>
					{
						this.state.formSelectItem.map(  item => ( <Row gutter={[ 10,16 ]} key={item} >
							<Col span={10}>
								{/*sourceCurrentSelected: '',targetCurrentSelected: '',*/}
								<Form.Item name={`${item}-left`} noStyle={true}>
									<Select key={`sourceCurrentSelected${item}`} style={{ width: 180 }} onChange={ value => this.handleSelectChange( value,'sourceCurrentSelected',item ) }>
										{
											this.state.sourceField.map( item => {
												return (
													<Select.Option key={`${item.tempFieldName}s`}
																	   value={JSON.stringify( { original: item.originalFieldName, temp: item.tempFieldName } )}>
														{item.finalFieldDesc}
													</Select.Option>
												);
											} )
										}
									</Select>
								</Form.Item>
							</Col>
							<Col span={2}><span dangerouslySetInnerHTML={{ __html: '&nbsp' }} />=</Col>
							<Col span={10}>
								<Form.Item name={`${item}-right`} noStyle={true}>
									<Select key={`targetCurrentSelected${item}`} style={{ width: 180 }} onChange={ value => this.handleSelectChange( value,'targetCurrentSelected',item )}>
										{
											this.state.targetField.map( item => {
												return (
													<Select.Option key={`${item.tempFieldName}s`}
																	   value={JSON.stringify( { original: item.originalFieldName, temp: item.tempFieldName } )}>
														{item.finalFieldDesc}
													</Select.Option>
												);
											} )
										}
									</Select>
								</Form.Item>
							</Col>
							{
								item !== this.state.formSelectItem[this.state.formSelectItem.length - 1] ?( <Col span={1} onClick={() => this.handlFieldList( item )}><MinusCircleOutlined /></Col> )
									:<Col span={1}/>
							}
						</Row> ) )
					}
				</Form>
			</Modal>
		);
	}
}

export default AssociationModal;